

package org.apache.ocean.server;

import org.apache.commons.lang.*;
import org.apache.commons.io.*;
import java.util.concurrent.*;
import java.util.*;
import java.util.logging.*;

/**
 *
 * @author  Jason Rutherglen
 */
public class ProcessTask implements Callable {
  public static Logger log = Logger.getLogger(ProcessTask.class.getName());
  public String cmd;
  
  public ProcessTask(String cmd) {
    if (StringUtils.isBlank(cmd)) throw new IllegalArgumentException("cmd cannot be blank");
    
    this.cmd = cmd;
  }
  
  public TaskLogXML call() throws Exception {
    int exitValue = -9999;
    String stdout = null;
    try {
      List cmdList = Arrays.asList(StringUtils.splitByWholeSeparator(cmd, null));
      
      ProcessBuilder processBuilder = new ProcessBuilder(cmdList);
      processBuilder.redirectErrorStream(true);
      
      Process process = processBuilder.start();
      stdout = IOUtils.toString(process.getInputStream());
      exitValue = process.waitFor();
      
      log.log(Level.INFO, "cmd: "+cmd+" exitValue: "+exitValue);
      
      return new TaskLogXML("ProcessTask: "+cmd, new Integer(exitValue), stdout);
    } catch (Throwable ex) {
      if (exitValue == -9999) {
        return new TaskLogXML("ProcessTask: "+cmd, stdout, ex);
      }
      return new TaskLogXML("ProcessTask: "+cmd, new Integer(exitValue), stdout, ex);
    }
  }
}
